﻿using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
using System.Net;

namespace Network.Library
{
    public static class HttpHelper
    {
        /// <summary>
        /// HttpContext 对象
        /// </summary>
        public static HttpContext HttpContextInfo => HttpContextHelper.HttpContext;

        /// <summary>
        /// 获取JwtUserId
        /// </summary>
        /// <returns></returns>
        public static string GetJwtUserId() 
        {
            var result = string.Empty;
            try
            {
                result= HttpContextInfo.User.FindFirst("id").Value;
                //var claims = HttpContextInfo.User.Claims.ToList();
                //var id = claims.Find(o => o.Type == "id");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        /// <summary>
        /// 判断是否是ajax请求
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsAjaxRequest(this HttpRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            return (request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest");
        }

        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {
            string result = HttpContextHelper.HttpContext.Connection.RemoteIpAddress.ToString();
            if (result.Equals("::1"))
            {
                IPHostEntry myEntry = Dns.GetHostEntry(Dns.GetHostName());
                result= myEntry.AddressList.FirstOrDefault(e => e.AddressFamily.ToString().Equals("InterNetwork")).ToString();
            }
            return result;
        }

        /// <summary>
        /// 获取本机局域网IP
        /// </summary>
        /// <returns></returns>
        public static string GetInternalIp()
        {
            IPHostEntry myEntry = Dns.GetHostEntry(Dns.GetHostName());
            return myEntry.AddressList.FirstOrDefault(e => e.AddressFamily.ToString().Equals("InterNetwork")).ToString();
        }

    }
}
